package com.qbadroid;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;

public class DatabaseActivity extends Activity {

	private TextView data;
	private Cursor countriesCursor;
	private DatabaseAdapter myDBAdapter;
	private List <Country> countries = new ArrayList<Country>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.database);
		
		data = (TextView)findViewById(R.id.TextView06);
		
		Country poland = new Country("Polska", "PL");
		Country germany = new Country("Niemcy", "DE");
		Country england = new Country("Anglia", "EN");
		
		myDBAdapter = new DatabaseAdapter(getApplicationContext());
		myDBAdapter.open();
		
		if(myDBAdapter.isEmpty())
		{
			myDBAdapter.insert(poland);
			myDBAdapter.insert(germany);
			myDBAdapter.insert(england);
		}
		
		fillCountriesList();
		fillListView();
		
		myDBAdapter.close();
	}
	
	private void fillListView()
	{
		for(Country country : countries)
		{
			data.setText(data.getText() + country.getCountryShortcut() + " " + country.getCountryName() + "\n");
		}
	}
	
	private void fillCountriesList()
	{
		countriesCursor = myDBAdapter.getAllEntries();
		startManagingCursor(countriesCursor);
		updateCountriesList();
	}
	
	private void updateCountriesList()
	{
		countriesCursor.requery();
		countries.clear();
		
		if(countriesCursor.moveToFirst())
		{
			do{
				String country = countriesCursor.getString(DatabaseAdapter.COUNTRY_COLUMN);
				String shortcut = countriesCursor.getString(DatabaseAdapter.SHORTCUT_COLUMN);
				Country newCountry = new Country(country, shortcut);
				countries.add(newCountry);
			}
			while(countriesCursor.moveToNext());
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			Intent result = new Intent(DatabaseActivity.this, MainMenu.class);
			result.putExtra("result", "result from database");
			setResult(2, result);
			//startActivity(result);
			finish();
		}
		
		return super.onKeyDown(keyCode, event);
		
	}
	
	@Override
	protected void onDestroy() {
		myDBAdapter.close();
		super.onDestroy();
	}
}
